<template>
  <div class="app-container">
    <div class="header">
      <el-form :inline="true" :model="queryParams" ref="ruleFormRef">
        <el-form-item label="参数名称" prop="configName">
          <el-input
            v-model="queryParams.configName"
            placeholder="请输入参数名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input
            v-model="queryParams.configKey"
            placeholder="请输入参数键名"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="系统内置" prop="configType">
          <el-select v-model="queryParams.configType" placeholder="系统内置" clearable>
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            type="daterange"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="defaultTime"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="footer">
      <div class="util">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:config:add']"
          >新增
        </el-button>

        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:config:remove']"
          >删除
        </el-button>

        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:config:export']"
          >导出
        </el-button>

        <el-button
          type="danger"
          plain
          icon="Refresh"
          @click="handleRefreshCache"
          v-hasPermi="['system:config:remove']"
          >刷新缓存
        </el-button>
      </div>

      <div class="table-inner">
        <el-table
          v-if="refreshTable"
          :default-expand-all="isExpandAll"
          v-loading="loading"
          row-key="deptId"
          :data="tableData"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="参数主键" align="center" prop="configId" />
          <el-table-column
            label="参数名称"
            align="center"
            prop="configName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="参数键名"
            align="center"
            prop="configKey"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="参数键值"
            align="center"
            prop="configValue"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="系统内置" align="center" prop="configType">
            <template #default="scope">
              <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.configType" />
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            align="center"
            prop="remark"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <!--            <template slot-scope="scope">
                          <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>-->
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:config:edit']"
                >修改
              </el-button>
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:config:remove']"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <!--分页器            -->
        <el-pagination
          style="margin-top: 40px"
          v-show="total > 0"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :background="true"
          layout="prev, pager, next, jumper, ->,  sizes, total"
          :total="total"
          @current-change="getList"
          @size-change="getList"
        />
      </div>
    </div>
    <!--对话框    -->
    <ConfigDialog ref="configDialogRef" @getList="getList" />
  </div>
</template>

<script lang="ts" setup>
  import { ElMessageBox, ElMessage, FormInstance } from 'element-plus'
  import { getCurrentInstance, nextTick, onMounted, reactive, ref } from 'vue'
  import { reqPostDeleteUrl, reqPostPageListUrl } from '@/api/system/post'
  import DictTag from '@/components/DictTags/index.vue'
  import { reqTableData } from '@/api/type'
  import { reqDelConfig, reqListConfig, reqRefreshCache } from '@/api/system/config'
  import ConfigDialog from './components/configDialog.vue'
  import { reqDelLogininfor } from '@/api/monitor/logininfor'

  const tableData = ref() /*表格的数据*/
  const loading = ref(true) // 遮罩层
  const dialogVisible = ref(false)
  const ruleFormRef = ref<FormInstance>()
  const refreshTable = ref(true) // 重新渲染表格状态
  const isExpandAll = ref(true) // 是否展开，默认全部折叠
  const total = ref(0) /*总计*/
  const configDialogRef = ref() /*对话框ref*/
  // 非单个禁用---判断修改按钮是否可用
  const single = ref(true)
  // 非多个禁用---判断删除按钮
  const multiple = ref(true)
  const dateRange = ref([])
  // 多选框选中数据
  const ids = ref([]) // 非多个禁用
  const defaultTime = ref<[Date, Date]>([
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
  ])
  const { proxy }: any = getCurrentInstance()
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    configName: undefined,
    configKey: undefined,
    configType: undefined,
    beginTime: undefined,
    endTime: undefined,
  })

  onMounted(async () => {
    loading.value = true
    await handleQuery() //获取第一页的信息
    setTimeout(async () => {
      loading.value = false
    }, 500)
  })

  // 查询
  const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
  }

  const getList = async () => {
    loading.value = true
    queryParams.beginTime = dateRange.value[0]
    queryParams.endTime = dateRange.value[1]
    await reqListConfig(queryParams)
      .then((req: reqTableData) => {
        if (req.code === 200) {
          total.value = req.total
          tableData.value = req.rows
        }
      })
      .catch((e) => {
        console.log(e.message)
      })
    setTimeout(() => {
      loading.value = false
      queryParams.beginTime = ''
      queryParams.endTime = ''
    }, 500)
  }

  //重置
  const resetQuery = (formEl: FormInstance | undefined) => {
    formEl.resetFields()
    Object.keys(queryParams).forEach((key) => {
      if (key === 'pageSize') queryParams[key] = 10
      else if (key === 'pageNum') queryParams[key] = 1
      else queryParams[key] = undefined
    })
    dateRange.value = []
    /*再次查询*/
    getList() //获取第一页的信息
  }

  //添加
  const handleAdd = () => {
    configDialogRef.value?.show()
  }

  // 修改缓存
  const handleUpdate = (row: any) => {
    configDialogRef.value?.show(row)
  }

  // 导出缓存
  const handleExport = () => {
    // 调用接口
    proxy.$download(
      'system/config/export',
      { ...queryParams },
      `systemConfig_${new Date().getTime()}.xlsx`,
    )
  }

  // 刷新缓存
  const handleRefreshCache = async () => {
    await reqRefreshCache()
      .then(() => {
        proxy.$modal.msgSuccess('刷新成功')
        getList()
      })
      .catch(() => {})
  }

  // 删除
  const handleDelete = (row) => {
    const configIds = row.configId || ids.value
    proxy.$modal
      .confirm('是否确认删除访问编号为"' + configIds + '"的数据项？')
      .then(function () {
        return reqDelConfig(configIds)
      })
      .then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功')
      })
      .catch(() => {})
  }

  /*多选框*/
  const handleSelectionChange = (selection: any) => {
    ids.value = selection.map((item: any) => item.configId)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }
</script>

<script lang="ts">
  export default {
    dicts: ['sys_yes_no'],
  }
</script>

<style scoped lang="scss">
  @import './index';
</style>
